package com.jt.assistant.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.SystemClock
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.lifecycle.lifecycleOwner
import com.afollestad.materialdialogs.list.listItemsSingleChoice
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.DeviceUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.ToastUtils
import com.jt.assistant.R
import com.jt.assistant.base.GlobalConfig.JTMS_URL_BASE
import com.jt.assistant.bean.AppInfo
import com.jt.assistant.bean.UpdateAppBean
import com.jt.assistant.utils.NumberUtil
import com.jt.assistant.viewmodel.LoginViewModel
import com.open.hule.library.entity.AppUpdate
import com.open.hule.library.utils.UpdateManager
import com.orhanobut.logger.Logger
import com.tencent.mmkv.MMKV
import com.yzp.mvvmlibrary.base.BaseActivity
import kotlinx.android.synthetic.main.activity_setting.*
import me.jessyan.retrofiturlmanager.RetrofitUrlManager

/**
 * 设置
 */
class SettingActivity : BaseActivity<LoginViewModel>() {
    override fun layoutId(): Int = R.layout.activity_setting

    override fun initView(savedInstanceState: Bundle?) {
    }

    @SuppressLint("SetTextI18n")
    override fun initData() {
        tv_about.text = AppUtils.getAppVersionName() + " : " + AppUtils.getAppVersionCode()

    }

    var mHits = LongArray(3) //初始全部为0

    override fun initListener() {

        tv_update.setOnClickListener {
            viewModel.getUpgradeUlr()
        }

        tv_printer.setOnClickListener {
            startActivity(Intent(this@SettingActivity, BluetoothActivity::class.java))
        }

        tv_login_out.setOnClickListener {
            showDialog()
        }

        tv_about.setOnClickListener {
            System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
            mHits[mHits.size - 1] = SystemClock.uptimeMillis()
            if (mHits[0] >= SystemClock.uptimeMillis() - 500) listURLDialog()
        }

        viewModel.mGetUpgradeUlrValue.observe(this, androidx.lifecycle.Observer {
            Logger.e(GsonUtils.toJson(it))

            if (it.errorCode == 0)
                viewModel.getUpgrade(
                    "http://40.73.59.226:9001" + it.data.url,
                    AppInfo(
                        AppUtils.getAppPackageName(),
                        AppUtils.getAppVersionCode().toString(),
                        DeviceUtils.getMacAddress().toString()
                    )
                )
        })

        viewModel.mGetUpgradeValue.observe(this, androidx.lifecycle.Observer {
            if (it.isSuccess()) {
                update(it.data)
            } else {
                ToastUtils.showShort(it.errorMsg)
            }
        })
    }

    private fun update(data: UpdateAppBean) {
        //http://40.73.59.226:1889/api/apk/d8e14db8fa0d4724a64217e0098bc29e.apk
        Logger.e("http://40.73.59.226:9001" + data.upgradeUrl)
        // 更新的数据参数
        val appUpdate = AppUpdate.Builder()
            .newVersionUrl("http://40.73.59.226:9001" + data.upgradeUrl)
            .newVersionCode(data.versionName + " : " + data.versionCode)
            .updateResourceId(R.layout.dialog_update)
            .updateTitle(R.string.update_title)
            .updateContentTitle(R.string.update_content_lb)
            .updateInfo(data.upgradeMsg.replace(" ", "\n"))
            .md5(data.md5)
            .downBrowserUrl("http://40.73.59.226:9001" + data.upgradeUrl)
            .isSilentMode(false)
            .updateProgressColor(Color.BLUE)
            .build()
        UpdateManager().startUpdate(this, appUpdate)
    }

    private fun showDialog() {
        MaterialDialog(this@SettingActivity).show {
            title(null, "是否确认退出登录?")
            cornerRadius(8f)
            positiveButton(null, "确定") {
                MMKV.defaultMMKV().putString("ROLENAMELIST", "")
                MMKV.defaultMMKV().putString("NAME", "")
                MMKV.defaultMMKV().putString("TOKEN", "")
                MMKV.defaultMMKV().putString("USERNAME", "")
                MMKV.defaultMMKV().putString("PASSWORD", "")
                AppUtils.relaunchApp()
                dismiss()
            }
            negativeButton(null, "取消") {
                dismiss()
            }
            lifecycleOwner(this@SettingActivity)
        }
    }

    private fun listURLDialog() {
        val list = ArrayList<String>()
        list.add(JTMS_URL_BASE)
//        list.add(JTMS_URL_BASE_2)

        MaterialDialog(this).show {
            listItemsSingleChoice(
                items = list
            ) { _, indices, text ->
                RetrofitUrlManager.getInstance().setGlobalDomain(text.toString())
                ToastUtils.showShort("URL:$text")
            }
            positiveButton(text = "确定选择")
            lifecycleOwner(this@SettingActivity)
        }
    }

}
